#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 10:36
import json
from os import path, sep
from typing import List

from config.config import config
from domain.report.common.period_enum import PeriodEnum
from domain.report.dto.basic_info_dto import BasicInfoDTO
from domain.report.spider.xbrl_sse.basic_info_spider import basicInfo_spider
from domain.report.spider.xbrl_sse.assembler import xbrl2dtos


basic_info_prefix_path = path.join(config.get("data", "folder"), "report")


def insert(basic_info:BasicInfoDTO) -> bool:
    if not basic_info or contain(basic_info):
        return False
    basic_path = f"{basic_info_prefix_path}{sep}{basic_info.stock_code}{sep}basic_info_{basic_info.period}.json"
    with open(basic_path, "a", encoding="utf-8") as file:
        file.write(json.dumps(basic_info.__dict__))
        return True


def insert_batch(basic_info_list:List[BasicInfoDTO]) -> bool:
    if not basic_info_list or len(basic_info_list) == 0:
        return False
    for dto in basic_info_list:
        if not contain(dto):
            insert(dto)
    return True


def get(stock_code:str, year:int, period:PeriodEnum) -> BasicInfoDTO:
    basic_path = f"{basic_info_prefix_path}{sep}{stock_code}{sep}basic_info_{period}.json"
    basic_info = None
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            basic_info_dict = json.loads(line)
            if basic_info_dict["year"] == year:
                basic_info = BasicInfoDTO()
                basic_info.__dict__ = basic_info_dict
                return basic_info
    basicInfo_dict = basicInfo_spider(stock_code, year, period)
    basic_dto_list = xbrl2dtos(basicInfo_dict, stock_code, period)
    insert_batch(basic_dto_list)
    for dto in basic_dto_list:
        if dto.year == year:
            return dto
    return None


def contain(basic_info:BasicInfoDTO) -> bool:
    if not basic_info:
        return False
    basic_path = f"{basic_info_prefix_path}{sep}{basic_info.stock_code}{sep}basic_info_{basic_info.period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            basic_info_dict = json.loads(line)
            if basic_info.stock_code == basic_info_dict["stock_code"] and basic_info.period == basic_info_dict["period"]:
                return True
    return False